import { defineStore } from 'pinia'
import { login } from '@/api/login'
import router from '../../router'

interface UserState {
  userinfo: object
  token: string
  permissions: Array<string>
}
export const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    userinfo: {},
    token: '',
    permissions: [],
  }),
  getters: {
    getUserinfo(): object {
      return this.userinfo
    },
    getToken(): string {
      return this.token
    },
    getPermissions(): Array<string> {
      return this.permissions
    },
  },
  actions: {
    setPermissions(permissions: any) {
      this.permissions = permissions
    },
    setUserinfo(userinfo: any) {
      this.userinfo = userinfo
    },
    async login(userinfo: any) {
      const res = await login(userinfo)
      if (res.code === 0) {
        this.setUserinfo(res.data)
        this.token = (res.data as any).token
        window.sessionStorage.setItem('token', (res.data as any).token)
        window.sessionStorage.setItem('userInfo', res.data as any)
      }
      return res
    },
    logout() {
      window.sessionStorage.removeItem('token')
      window.sessionStorage.removeItem('userInfo')
      this.userinfo = {}
      this.token = ''
      router.replace('/login')
    },
  },
  persist: {
    enabled: true,
  },
})
